import React, { Component } from 'react';
import { connect } from 'dva';
import find from 'lodash/find';
import memoizeOne from 'memoize-one';
import isEqual from 'lodash/isEqual';
import { Redirect } from 'umi';
import { getItem } from '@/utils/utils';

class Iframe extends Component {
  constructor(props) {
    super(props);
    this.findMenu = memoizeOne(this.findMenu, isEqual);
  }

  /**
   * 查找对应的菜单信息
   * @return {object|undefined}
   */
  findMenu = (menuId, all) => {
    return find(all, { menuId: parseInt(menuId, 10) });
  };

  render() {
    const {
      match: {
        params: { menuId },
      },
      size,
      all,
    } = this.props;

    const menu = this.findMenu(menuId, all);

    if (menu === undefined || !/^\[iframe\]http+/.test(menu.urlAddr)) {
      // throw new Error('urlAddr format is error or the menuId is not in the menu');
      return <Redirect to="/404" />;
    }

    let address = menu.urlAddr.split('[iframe]')[1];
    const { sessionId } = getItem('user');

    // 根据原连接是否带?, 决定用什么符号追加 bss3SessionId
    if (address.indexOf('?') === -1) {
      address = `${address}?bss3SessionId=${sessionId}`;
    } else {
      address = `${address}&bss3SessionId=${sessionId}`;
    }

    return (
      <iframe
        title={menu.menuName}
        src={address}
        frameBorder="0"
        height={size.height}
        width="100%"
        style={{ backgroundColor: '#fff' }}
      />
    );
  }
}

export default connect(({ menu, setting }) => ({
  all: menu.all,
  size: setting.size,
}))(Iframe);
